<template>
  <div class="disposal-container">
    <!-- 头部工具栏 -->
    <div class="header">
      <el-button type="primary" @click="handleAdd">添加报废记录</el-button>
    </div>

    <!-- 列表 -->
    <el-table
      :data="disposalList"
      style="width: 100%; margin-top: 20px"
      v-loading="loading"
      border
      stripe
      :header-cell-style="{ background: '#f5f7fa' }"
    >
      <el-table-column prop="deviceId" label="设备名称" min-width="150">
        <template #default="scope">
          <span>{{ getDeviceName(scope.row.deviceId) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="disposalDate" label="报废日期" width="120">
        <template #default="scope">
          <span>{{ formatDate(scope.row.disposalDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="disposalReason" label="报废原因" min-width="200" show-overflow-tooltip />
      <el-table-column prop="disposalMethod" label="处置方式" width="100">
        <template #default="scope">
          <el-tag
            :type="getDisposalMethodType(scope.row.disposalMethod)"
            size="small"
          >
            {{ scope.row.disposalMethod }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="disposalAmount" label="处置金额" width="120" align="right">
        <template #default="scope">
          <span>¥{{ formatAmount(scope.row.disposalAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="processedBy" label="经办人" width="120">
        <template #default="scope">
          <el-tooltip
            :content="getUserInfo(scope.row.processedBy)"
            placement="top"
            effect="light"
          >
            <span>{{ getUserName(scope.row.processedBy) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="approverId" label="审批人" width="120">
        <template #default="scope">
          <el-tooltip
            :content="getUserInfo(scope.row.approverId)"
            placement="top"
            effect="light"
          >
            <span>{{ getUserName(scope.row.approverId) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            link
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            link
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        :model="form"
        label-width="100px"
        ref="formRef"
        :rules="rules"
        class="disposal-form"
      >
        <el-form-item label="设备" prop="deviceId">
          <el-select
            v-model="form.deviceId"
            placeholder="请选择设备"
            filterable
            :disabled="form.disposalId"
            style="width: 100%"
          >
            <el-option
              v-for="device in deviceList"
              :key="device.deviceId"
              :label="device.deviceName"
              :value="device.deviceId"
            >
              <span style="float: left">{{ device.deviceName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ device.deviceNo }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报废日期" prop="disposalDate">
          <el-date-picker
            v-model="form.disposalDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="报废原因" prop="disposalReason">
          <el-input
            v-model="form.disposalReason"
            type="textarea"
            :rows="3"
            placeholder="请输入报废原因"
          />
        </el-form-item>
        <el-form-item label="处置方式" prop="disposalMethod">
          <el-select
            v-model="form.disposalMethod"
            placeholder="请选择处置方式"
            style="width: 100%"
          >
            <el-option label="回收" value="recycled">
              <el-icon style="margin-right: 8px; color: #67c23a"><Refresh /></el-icon>回收
            </el-option>
            <el-option label="销毁" value="destroyed">
              <el-icon style="margin-right: 8px; color: #f56c6c"><Delete /></el-icon>销毁
            </el-option>
            <el-option label="捐赠" value="donated">
              <el-icon style="margin-right: 8px; color: #409eff"><Present /></el-icon>捐赠
            </el-option>
            <el-option label="售卖" value="sold">
              <el-icon style="margin-right: 8px; color: #909399"><Money /></el-icon>售卖
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处置金额" prop="disposalAmount">
          <el-input-number
            v-model="form.disposalAmount"
            :precision="2"
            :step="100"
            :min="0"
            style="width: 100%"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="经办人" prop="processedBy">
          <el-select
            v-model="form.processedBy"
            placeholder="请选择经办人"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.fullName"
              :value="user.userId"
            >
              <span style="float: left">{{ user.fullName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ user.username }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审批人" prop="approverId">
          <el-select
            v-model="form.approverId"
            placeholder="请选择审批人"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.fullName"
              :value="user.userId"
            >
              <span style="float: left">{{ user.fullName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ user.username }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, More, Present, Refresh } from '@element-plus/icons-vue'
import { addDisposal, getDisposalList, updateDisposal, deleteDisposal } from '@/api/disposal'
import { queryDevices } from '@/api/device'
import { getUserListService } from '@/api/user'
import { formatDate, formatAmount } from '@/utils/format'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const disposalList = ref([])
const deviceList = ref([])
const userList = ref([])

const form = ref({
  deviceId: '',
  disposalDate: formatDate(new Date()),
  disposalReason: '',
  disposalMethod: '',
  disposalAmount: 0,
  processedBy: '',
  approverId: ''
})

const rules = {
  deviceId: [{ required: true, message: '请选择设备', trigger: 'change' }],
  disposalDate: [{ required: true, message: '请选择报废日期', trigger: 'change' }],
  disposalReason: [{ required: true, message: '请输入报废原因', trigger: 'blur' }],
  disposalMethod: [{ required: true, message: '请选择处置方式', trigger: 'change' }],
  processedBy: [{ required: true, message: '请选择经办人', trigger: 'change' }],
  approverId: [{ required: true, message: '请选择审批人', trigger: 'change' }]
}

const formRef = ref()

// 获取设备名称
const getDeviceName = (deviceId) => {
  const device = deviceList.value.find(d => d.deviceId === deviceId)
  return device ? device.deviceName : deviceId
}

// 获取用户名称
const getUserName = (userId) => {
  const user = userList.value.find(u => u.userId === userId)
  return user ? user.fullName : userId
}

// 获取用户详细信息
const getUserInfo = (userId) => {
  const user = userList.value.find(u => u.userId === userId)
  return user ? `${user.fullName} - ${user.username}` : userId
}

// 获取处置方式对应的标签类型
const getDisposalMethodType = (method) => {
  const typeMap = {
    '回收': 'success',
    '销毁': 'danger',
    '捐赠': 'primary',
    '其他': 'info'
  }
  return typeMap[method] || 'info'
}

// 获取列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getDisposalList()
    if (res.code === 200) {
      disposalList.value = res.data
    }
  } catch (error) {
    console.error('获取报废记录列表失败:', error)
    ElMessage.error('获取报废记录列表失败')
  }
  loading.value = false
}

// 获取设备列表
const fetchDevices = async () => {
  try {
    const res = await queryDevices({})
    if (res.code === 200) {
      // 只显示在库的设备
      deviceList.value = res.data.filter(device => device.status === 'in_stock')
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    const res = await getUserListService()
    if (res.code === 200) {
      userList.value = res.data.records
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 添加
const handleAdd = () => {
  dialogTitle.value = '添加报废记录'
  form.value = {
    deviceId: '',
    disposalDate: formatDate(new Date()),
    disposalReason: '',
    disposalMethod: '',
    disposalAmount: 0,
    processedBy: '',
    approverId: ''
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑报废记录'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该报废记录吗？此操作不可恢复',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteDisposal(row.disposalId)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchData()
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const submitData = { ...form.value }
        let res

        if (submitData.disposalId) {
          res = await updateDisposal(submitData)
        } else {
          res = await addDisposal(submitData)
        }

        if (res.code === 200) {
          ElMessage.success(submitData.disposalId ? '更新成功' : '添加成功')
          dialogVisible.value = false
          fetchData()
          // 如果是新增，刷新设备列表
          if (!submitData.disposalId) {
            fetchDevices()
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

onMounted(() => {
  fetchData()
  fetchDevices()
  fetchUsers()
})
</script>

<style scoped>
.disposal-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.disposal-form :deep(.el-form-item__content) {
  justify-content: flex-start;
}

:deep(.el-input-number .el-input__wrapper) {
  width: 100%;
}

:deep(.el-select-dropdown__item) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
